import cv2 as cv
import threading
import Process.processmethod as process
import queue
import GaussianBlur.Gaussianmethod as Gaussian

# 创建任务队列
frame_queue = queue.Queue(maxsize=5)  # 调整队列大小
encrypt_queue = queue.Queue(maxsize=5)


def main():
    def video_capture_thread():
        cap = cv.VideoCapture(0)
        if not cap.isOpened():
            print("Error: Unable to open the camera.")
            return

        while True:
            ret, frame = cap.read()
            if not ret:
                print("Error: Unable to read from the camera.")
                break
            if not frame_queue.full():
                frame_queue.put(frame)

    def face_detection_thread():
        while True:
            frame = frame_queue.get()
            try:
                frame = cv.convertScaleAbs(frame)
                frame, facelocation = process.detect_face(frame)
                if facelocation is not None:
                    encrypt_queue.put((frame, facelocation))
            except Exception as e:
                print(f"Error in face detection: {e}")
            frame_queue.task_done()

    def image_encryption_thread():
        frame_count = 0
        while True:
            frame, facelocation = encrypt_queue.get()
            try:
                process.getencodings(frame, facelocation)
                mask = process.create_mask(frame, facelocation)
                frame = Gaussian.Gaussian(mask, frame)

                # 每处理10帧显示一次
                if frame_count % 10 == 0:
                    cv.imshow('Encrypted Frame', frame)
                frame_count += 1

                if cv.waitKey(1) & 0xFF == ord('q'):
                    break
            except Exception as e:
                print(f"Error in image encryption: {e}")
            encrypt_queue.task_done()

    threads = []
    threads.append(threading.Thread(target=video_capture_thread))
    threads.append(threading.Thread(target=face_detection_thread))
    threads.append(threading.Thread(target=image_encryption_thread))

    for thread in threads:
        thread.daemon = True
        thread.start()

    # 等待用户输入以保持主线程活动
    try:
        while True:
            pass
    except KeyboardInterrupt:
        print("Program terminated by user.")


if __name__ == '__main__':
    main()
